#include <iostream>
using namespace std;

//2. 使用引用注意事项
void test02()
{
    //1) 引用必须初始化
    //int& ref; //报错:必须初始化引用
    //2) 引用一旦初始化，不能改变引用
    int a = 10;
    int b = 20;
    int &ref = a;
    ref = b; //不能改变引用
    //3) 不能对数组建立引用
    int arr[10];
    //int& ref3[10] = arr;
}
//对数组使用引用
void test03()
{
    //1. 建立数组引用方法一
    //使用typedef为现有类型创建别名，定义易于记忆的类型名
    typedef int ArrRef[10];
    int arr[10];
    ArrRef &aRef = arr;
    for (int i = 0; i < 10; i++)
    {
        aRef[i] = i + 1;
    }
    for (int i = 0; i < 10; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    //2. 建立数组引用方法二
    int(&f)[10] = arr;
    for (int i = 0; i < 10; i++)
    {
        f[i] = i + 10;
    }
    for (int i = 0; i < 10; i++)
    {
        cout << arr[i] << " ";
    }
}

//值传递
void ValueSwap(int m, int n)
{
    int temp = m;
    m = n;
    n = temp;
}
//地址传递
void PointerSwap(int *m, int *n)
{
    int temp = *m;
    *m = *n;
    *n = temp;
}
//引用传递
void ReferenceSwap(int &m, int &n)
{
    int temp = m;
    m = n;
    n = temp;
}
void test()
{
    int a = 10;
    int b = 20;
    //值传递
    ValueSwap(a, b);
    cout << "a:" << a << " b:" << b << endl;
    //地址传递
    PointerSwap(&a, &b);
    cout << "a:" << a << " b:" << b << endl;
    //引用传递
    ReferenceSwap(a, b);
    cout << "a:" << a << " b:" << b << endl;

    //通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单
    //1) 函数调用时传递的实参不必加“&”符
    //2) 在被调函数中不必在参数前加“*”符
    //引用的本质在c++内部实现是一个指针常量
}

//const int& param防止函数中意外修改数据
void ShowVal(const int& param){
	cout << "param:" << param << endl;
}


int main()
{
    //引用就是对变量起别名
    cout << "hello" << endl;
    int a = 10;
    //给变量a取一个别名b
    int &b = a;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    cout << "------------" << endl;
    //操作b就相当于操作a本身

    //一个变量可以有n个别名
    int &c = a;
    c = 200;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    cout << "c:" << c << endl;
    cout << "------------" << endl;
    //a,b,c的地址都是相同的

    test();

    system("pause");
    return 0;
}
